<?php

namespace common\utils;


use Yii;
use yii\log\LogRuntimeException;
use yii\base\Exception;
use yii\helpers\VarDumper;

class DbLogUtil extends \yii\log\DbTarget
{

    /**
     * Stores log messages to DB.
     * Starting from version 2.0.14, this method throws LogRuntimeException in case the log can not be exported.
     * @throws Exception
     * @throws LogRuntimeException
     */
    public function export()
    {
        if ($this->db->getTransaction()) {
            // create new database connection, if there is an open transaction
            // to ensure insert statement is not affected by a rollback
            $this->db = clone $this->db;
        }
 
        $session_id = Yii::$app->session->id ?? '';
        $app_id = Yii::$app->id ?? '';
        $module = Yii::$app->controller->module->id ?? '';
        $controller = Yii::$app->controller->id ?? '';
        $action = Yii::$app->controller->action->id ?? '';
        $tableName = $this->db->quoteTableName($this->logTable);
        $created_id = '100007';
        $created_at = time();


        $sql = "INSERT INTO $tableName ([[session_id]], [[user_id]], [[app_id]], [[module]], [[controller]], [[action]], [[remark]], [[created_id]], [[created_at]])
                VALUES (:session_id, :user_id,  :app_id,  :module,  :controller,  :action,  :message,  :created_id,  :created_at)";
        $command = $this->db->createCommand($sql);
        foreach ($this->messages as $message) {
            list($text, $level, $category, $timestamp) = $message;
            if (!is_string($text)) {
                // exceptions may not be serializable if in the call stack somewhere is a Closure
                if ($text instanceof \Throwable || $text instanceof \Exception) {
                    $text = (string) $text;
                } else {
                    $text = VarDumper::export($text);
                }
            }
            if ($command->bindValues([
                    ':session_id' => $session_id ,
                    ':user_id' => Yii::$app->user->identity->id ?? 0,
                    ':app_id' => $app_id,
                    ':module' => $module,
                    ':controller' => $controller,
                    ':action' => $action,
                    ':message' => $text,
                    ':created_id' => $created_id,
                    ':created_at' => $created_at,
                    
                ])->execute() > 0) {
                continue;
            }
            throw new LogRuntimeException('Unable to export log through database!');
        }

    }


}

	